import taichi as ti

from .plane import Plane
from ..utils import Vec2, Vec3, Inf, eps, Ray3


class Triangle2d(Plane):
    """平面三角形"""

    def __init__(self: int, p1: Vec2, p2: Vec2):
        super().__init__()
        p1, p2 = Vec2(p1), Vec2(p2)
        Plane.shapes[self.index].attribute[0] = p1.x
        Plane.shapes[self.index].attribute[1] = p1.y
        Plane.shapes[self.index].attribute[2] = p2.x
        Plane.shapes[self.index].attribute[3] = p2.y

    @ti.func
    def intersect(self: int, ray: Ray3, closest: float):
        """Moller Trumbore Algorithm"""
        p1 = Vec3(Plane.shapes[self].attribute[:2], 0)
        p2 = Vec3(Plane.shapes[self].attribute[2:4], 0)
        s1, s2 = ray.direct.cross(p2), ray.origin.cross(p1)
        t, b1, b2 = Vec3(s2.dot(p2), s1.dot(ray.origin), s2.dot(ray.direct)) / s1.dot(
            p1
        )
        if t < eps or t >= closest or b1 < 0 or b2 < 0 or b1 + b2 > 1:
            t = Inf
        return t, Vec3(0, 0, 1)
